package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.UserLikeVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

@DubboService
public class VisitorServiceImpl implements VisitorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Visitor> findeAccessUser(Long userId, Long lastLoginTime) {
        // 1.构建条件
        Query query = Query.query(Criteria.where("userId").is(userId).and("date").gt(lastLoginTime))
                .skip(0).limit(5);

        // 2.查询
        List<Visitor> visitorList = mongoTemplate.find(query, Visitor.class);

        // 3.返回
        return visitorList;
    }


    @DubboReference
    private UserInfoService userInfoService;

    /**
     * 分页查询最近访问
     * @Author: bug
     */
    @Override
    public PageBeanVo findVisitorByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 创建查询条件
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((pageNum - 1) * pageSize).limit(pageSize);
        // 查询
        List<Visitor> list = mongoTemplate.find(query, Visitor.class);
        // 声明voList
        List<UserLikeVo> voList = new ArrayList<>();
        // 遍历
        if (CollectionUtil.isNotEmpty(list)) {
            for (Visitor visitor : list) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();
                vo.setUserInfo(userInfoService.findUserInfoById(visitor.getVisitorUserId()));
                // 添加进voList
                voList.add(vo);
            }
        }
        // 查询总数
        long total = mongoTemplate.count(query, Visitor.class);

        // 封装并返回分页对象
        return new PageBeanVo(pageNum,pageSize,total,voList);
    }
}
